<template>
<uni-shadow-root class="partials-locateAddress-index"><block v-if="setting&&setting.platformSetting">
    <block v-if="receiveData.androidTemplate == ''&&receiveData.jsonData">
        
        <view class="simple_locate_address" :style="'background:'+(receiveData.jsonData.bgColor)" data-link="select_address.html" @click="tolinkUrl">
          <view class="simple_locate_address_left">
             <image mode="aspectFill" class="simple_locate_address_icon" :src="receiveData.jsonData.icon||'https://image1.sansancloud.com/xianhua/2019_4/18/15/19/20_707.jpg?x-oss-process=style/preview_120'"></image>
             <text class="simple_locate_address_text" :style="'color:'+(receiveData.jsonData.fontColor)">{{locationAddress}}</text>
             <image class="simple_locate_address_right" mode="aspectFill" src="https://image1.sansancloud.com/xianhua/2019_4/18/16/46/26_395.jpg?x-oss-process=style/preview_120"></image>
          </view>
          <image v-if="setting.platformSetting.logo&&clientNo=='naifen'" :src="setting.platformSetting.logo" class="logo"></image>
        </view>
    </block>
    <block v-if="receiveData.androidTemplate == 'location_area'&&receiveData.jsonData">
        
        <view class="location_area_block" :style="'background:'+(receiveData.jsonData.bgColor)+';color: '+(receiveData.jsonData.fontColor)+';'">
            <view class="location_area_info" :data-link="'select_area.html?location_area='+(locationArea)" @click="tolinkUrl">
                <image :src="receiveData.jsonData.icon||'https://image1.sansancloud.com/gongyixiangmu/2019_12/31/18/44/26_612.jpg?x-oss-process=style/preview_120'" class="location_area_icon"></image>
                <text class="location_area_name">{{locationArea||'暂无区域'}}</text>
                
            </view>
            <view class="location_area_search">
                <image src="https://image1.sansancloud.com/xianhua/2020_1/6/11/13/19_520.jpg?x-oss-process=style/preview_120" class="location_area_search_icon"></image>
                <input class="location_area_search_input" :placeholder="receiveData.jsonData.searchTip" data-link="search_page.html" @click="tolinkUrl"></input>
            </view>
        </view>
    </block>
    
</block></uni-shadow-root>
</template>

<script>

global['__wxRoute'] = 'partials/locateAddress/index'
const app = getApp();
Component({
  properties: {
    receiveData: {
      type: JSON,
      value: 'default value',
    }
  },
  data: {
    someData: {},
    page:"1",
    shops:[],
    journey:[],//公里数
    locationAddress:"加载当前地址中...",
    locationArea:"加载中...",
    clientNo:'',
  },
  ready:function(){
    let that=this;
    this.setData({
      setting: app.globalData.setting,
      clientNo: app.globalData.clientNo
    })
    console.log("================locationAddress============",that.data.receiveData)
    if(that.data.receiveData.androidTemplate == "location_area"){
        that.getLocationArea();
    }else{
        that.getLocationAddress();
    }
    if (app.globalData.setting.platformSetting.defaultColor && app.globalData.setting.platformSetting.defaultColor !=""){
      // 有默认色
      this.setData({
        defaultColor: app.globalData.setting.platformSetting.defaultColor
      })
    }
    else{
      // 没有默认色
      this.setData({
        defaultColor: app.globalData.setting.platformSetting.defaultColor
      })
    }
  },
  methods: {
    getLocationArea:function(){
      let that=this;
      console.log("==========getLocationArea=========")
      let locationAreaData = wx.getStorageSync('selectAreaData')||''
      if (locationAreaData){
        console.log("拥有区域", locationAreaData)
        that.setData({ locationArea: locationAreaData.areaName })
        let params={areaId:locationAreaData.id||0};
        that.setAreaDataFun(params);
      } else {
        console.log("未拥有地址", locationAreaData)
        wx.getLocation({
          type: 'gcj02',
          success: function (res) {
            console.log("=====getLocationArea====", res)
            let latitude = res.latitude
            let longitude = res.longitude
            console.log(longitude + "..............." + latitude)
            // 获取附近店铺数据
            let pageParam = {
              "longitude": longitude,
              "latitude": latitude,
            }
            console.log(pageParam)
            that.getLoctionArea(pageParam);
          },
          fail: function (res) {
            console.log("===res-fail===", res)
          }
        })
      }
    },
    setAreaDataFun:function(params){
        let that=this;
        var customIndex = getApp().globalData.AddClientUrl("/setLocateArea.html", params, 'post');
        wx.request({
          url: customIndex.url,
          data:customIndex.params,
          header: getApp().globalData.headerPost,
          method: 'POST',
          success: function (res) {
            console.log("=====getAllAreaFun====", res.data);
            let data = res.data.relateObj;
            if(res.data.errcode==0){
              console.log("设置成功", that.selectAddressData);
            }else{
              wx.showToast({
                title: res.data.errMessage,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              })
            }
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
            getApp().globalData.loadFail();
          }
        });
    },
    getLoctionArea:function(pageParam){
        let that = this
        let param = {}
        param['type'] = 1
        param.longitude = pageParam.longitude
        param.latitude = pageParam.latitude
        var customIndex = app.globalData.AddClientUrl("/wx_search_nearest_area.html", param, 'get')
        wx.request({
          url: customIndex.url,
          header: app.globalData.header,
          success: function (res) {
            console.log("=====getLoctionArea====", res.data)
            let data = res.data.relateObj
            let params={
              longitude: pageParam.longitude,
              latitude: pageParam.latitude,
              areaName: data.areaName,
              areaId: data.id
            }
            let locationArea;
            if (data.areaName){
              locationArea = data.areaName
            }else{
              locationArea = "加载失败..."
            }
            that.setData({ locationArea: locationArea })
            let setAreaDataParams={areaId:data.id||0};
            that.setAreaDataFun(setAreaDataParams);
            wx.hideLoading()
          },
          fail: function (res) {
            wx.hideLoading()
            app.globalData.loadFail()
          }
        })
    },
    changeSelectAddress: function (data,indexPage) {
      let that=this;
      console.log("====changeSelectAddress====", data)
      let locationAddress
      if (data.value) {
        locationAddress = data.value
      } else {
        locationAddress = data.province + data.city + data.area + data.address
      }
      that.setData({ locationAddress: locationAddress })
      if (indexPage && indexPage.onPullDownRefresh){
        indexPage.onPullDownRefresh();
      }
    },
    setLoctionAddr: function (pageParam) {
      let that = this
      let customIndex = app.globalData.AddClientUrl("/setLocation.html", pageParam, 'get')
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          console.log("=====setLoctionAddr====", res.data)
          wx.hideLoading()
        },
        fail: function (res) {
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    //  附近门店取第一个
    getNearMenDian: function (addressInfo) {
      let that = this;
      let latitude = addressInfo.latitude
      let longitude = addressInfo.longitude
      let menDian = {
        longitude: longitude,
        latitude: latitude,
      }  
      // 获取门店的样式
      let menDianYangShi = app.globalData.AddClientUrl("/find_mendians.html", menDian, 'get')
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: app.globalData.headerPost,
        method: 'GET',
        success: function (res) {
          console.log("===附近门店取第一个", res.data)
          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            })
          }
          else {
            let firstMendian = res.data.relateObj.result;
            if (firstMendian.length != 0 && firstMendian[0].id) {
              // 当数据都存在，然后就开始设置门店
              that.setUpMenDian(firstMendian[0].id);
            } else {
                console.log("您附近没有相关门店哦")
              // wx.showToast({
              //   title: "您附近没有相关门店哦!",
              //   image: '/wxcomponents/images/icons/tip.png',
              //   duration: 2000
              // })
            }
          }
        }
      })
    },
    // 设置门店（当门店信息都有的时候，将门店id传到服务器。）
    setUpMenDian: function (menDianID) {
      let that = this;
      let id = menDianID
      let menDianParameter = {
        mendianId: id
      }
      let menDianYangShi = app.globalData.AddClientUrl("/location_mendian.html", menDianParameter, 'get')
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: app.globalData.headerPost,
        method: 'GET',
        success: function (res) {
          console.log('=====setUpMenDian====', res)
          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            })
          }
          else {
            console.log("设置成功")
          }
        }
      })
    },
    // 这里是一个自定义方法
    tolinkUrl: function (e) {
      console.log("e.currentTarget.dataset.link=====", e.currentTarget.dataset.link)
      let linkUrl = e.currentTarget.dataset.link
      app.globalData.linkEvent(linkUrl)
    },
    getLocationAddress:function(){
      let that=this;
      console.log("==========getLocationAddress=========")
      let locationAddressData = wx.getStorageSync('selectAddressData')||''
      if (locationAddressData){
        console.log("拥有地址", locationAddressData)
        let locationAddress=""
        if (locationAddressData.community){
          if (locationAddressData.value && locationAddressData.community) {
            locationAddress = locationAddressData.value
          } else  {
            locationAddress = locationAddressData.province + locationAddressData.city + locationAddressData.area + locationAddressData.address
          }
          that.setData({ locationAddress: locationAddress })
        }
        console.log("===locationAddressData====", locationAddressData);
        let pageParam = {
          "longitude": locationAddressData.longitude,
          "latitude": locationAddressData.latitude,
        }
        that.getLoctionAddr(pageParam)
      } else {
        console.log("未拥有地址", locationAddressData)
        wx.getLocation({
          type: 'gcj02',
          success: function (res) {
            console.log("=====getLocationAddress====", res)
            let latitude = res.latitude
            let longitude = res.longitude
            console.log(longitude + "..............." + latitude)
            // 获取附近店铺数据
            let pageParam = {
              "longitude": longitude,
              "latitude": latitude,
            }
            console.log(pageParam)
            that.getLoctionAddr(pageParam)
            that.getNearMenDian(pageParam);
          },
          fail: function (res) {
            console.log("===res-fail===", res)
          }
        })
      }
    },
    // 获取地理数据
    getLoctionAddr: function (pageParam) {
      var that = this
      var param = {}
      param['type'] = 1
      param.longitude = pageParam.longitude
      param.latitude = pageParam.latitude
      var customIndex = app.globalData.AddClientUrl("/get_location_detail.html", param, 'get')
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          console.log("=====getLoctionAddr====", res.data)
          let data = res.data.result
          let params={
            longitude: pageParam.longitude,
            latitude: pageParam.latitude,
            province: data.addressComponent?data.addressComponent.province : data.address_component.province,
            city: data.addressComponent ?data.addressComponent.city : data.address_component.city,
            street: data.addressComponent ?data.addressComponent.street : data.address_component.street,
          }
          that.setLoctionAddr(params);
          let locationAddress;
          if (data.formatted_address || data.formatted_addresses){
            locationAddress = data.pois[0].title
          }else{
            locationAddress = "加载当前地址失败..."
          }
          that.setData({ locationAddress: locationAddress })
          wx.hideLoading()
        },
        fail: function (res) {
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
  getGreatCircleDistance: function (lng1, lat1, lng2, lat2){
    var EARTH_RADIUS = 6378.137; //地球半径
    lng1=parseFloat(lng1);
    lat1=parseFloat(lat1);
    lng2=parseFloat(lng2);
    lat2=parseFloat(lat2);
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = (lng1 * Math.PI / 180.0) - (lng2 * Math.PI / 180.0);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;
    s=s.toFixed(1);
    var journey = this.data.journey
    journey.push(s);
    this.setData({
      journey: journey
    })
    return s;
  },
  },
})
export default global['__wxComponents']['partials/locateAddress/index']
</script>
<style platform="mp-weixin">
@import 'gongyi_location_area/index.css';/* 引入滑动的附近店铺列表 */
.simple_locate_address{
  padding:10rpx 25rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.simple_locate_address_left{
  display: flex;
  align-items: center;
  width:86%;
}
.simple_locate_address_icon{
  width: 35rpx;
  height: 35rpx;
  margin-right: 10rpx;
}
.simple_locate_address_right{
  width: 30rpx;
  height: 30rpx;
  margin-left: 6rpx;
}
.simple_locate_address_text{
  font-size: 30rpx;
  font-weight: bold;
  width: 100%;
  text-overflow:ellipsis;
  white-space:nowrap;
  overflow:hidden;
}
.logo{
  width: 60rpx;
  height: 60rpx;
  border-radius: 60rpx;
  margin-right: 20rpx
}
</style>